package ru.amse.jsynchro.logging;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class FileLogger extends Logger {
    private final static String CLIENTFILE = "client.log";
    private final static String SERVERFILE = "server.log";
    private File file;
    FileLogger(boolean useTime, String source) {
        super(useTime, source);
        if ("Client".equals(source)) {
            file = new File(CLIENTFILE);
        }
        if ("Server".equals(source)) {
            file = new File(SERVERFILE);
        }
        if (file.exists()) {
            file.delete();
        }
    }

    public void exception(Exception e) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(file, true);
            writer.write(preLogMessage());
            writer.write(getStackTrace(e));
            writer.write("\n");
            writer.close();
        } catch (FileNotFoundException e1) {
            throw new AssertionError(e1);
        } catch (IOException e2) {
            e2.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    private String getStackTrace(Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter ps = new PrintWriter(sw);
        e.printStackTrace(ps);
        return sw.toString();
    }

    public void info(String message) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(file, true);
            writer.append(preLogMessage());
            writer.write(message);
            writer.write("\n");
            writer.close();
        } catch (FileNotFoundException e1) {
            throw new AssertionError(e1);
        } catch (IOException e2) {
            e2.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    
//    protected void finalize() throws Throwable {
//        writer.close();
//    }
//    
}
